<template>
	<el-dialog
		:model-value="visible"
		@update:model-value="emit('update:visible', $event)"
		title="编辑代理商"
		width="600px"
		@close="handleClose"
	>
		<el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
			<el-form-item label="代理层级" prop="agentlevel" disabled>
				<el-input v-model="formData.agentlevel" placeholder="代理层级" disabled></el-input>
			</el-form-item>

			<el-form-item label="代理商" prop="agentUserId">
				<agent-user-select
					ref="agentUserSelectRef"
					:agent-level="props.agentLevel"
					:agent-user-id="props.agentUserId"
					:function-type="'edit'"
					v-model="formData.agentUserId"
					:agent-obj="props.agentObj"
					:agent-change-type="'agent'"
				/>
			</el-form-item>

			<el-form-item label="代理商店铺" prop="agentShopIds">
				<agent-shop-select
					ref="agentShopSelectRef"
					v-model="formData.agentShopIds"
					:agent-obj="props.agentObj"
				/>
			</el-form-item>

			<el-form-item label="上级代理商" prop="parentId" v-if="props.agentLevel - 1 != 0">
				<!-- <agent-user-select
					:agent-level="props.agentLevel"
					:parent-agent-id="props.parentId"
					v-model="formData.parentAgentId"
					:agent-change-type="'leaderAgent'"
					:disabled="
						props.agentLevelNum == props.agentLevel && props.parentAgentName.length != 0
					"
				/> -->
				<agent-user-select
					ref="parentAgentUserSelectRef"
					:agent-user-id="props.parentId"
					:agent-level="props.agentLevel"
					:parent-agent-id="props.parentId"
					v-model="formData.parentAgentId"
					:function-type="'edit'"
					:agent-change-type="'leaderAgent'"
					:agent-obj="props.agentObj"
				/>
			</el-form-item>
		</el-form>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" @click="handleSubmit">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { service } from '/@/cool';
import { ElMessage } from 'element-plus';
import agentShopSelect from '../components/agent-shop-select.vue';
import agentUserSelect from './agent-user-select.vue';

const { t } = useI18n();

// Props
const props = defineProps({
	visible: {
		type: Boolean,
		default: false
	},
	parentId: {
		type: Number,
		default: 0
	},
	parentAgentName: {
		type: String,
		default: ''
	},
	agentLevel: {
		type: Number,
		required: true
	},
	agentLevelNum: {
		type: Number,
		required: true
	},
	shopId: {
		type: Number,
		default: 0
	},
	agentUserId: {
		type: Number,
		required: true
	},
	agentId: {
		type: Number,
		default: 0
	},
	agentShopIds: {
		type: Array,
		default: () => []
	},
	agentObj: {
		type: Object,
		default: () => ({})
	}
});

// Emits
const emit = defineEmits(['update:visible', 'success']);

// 表单引用
const formRef = ref();
const agentUserSelectRef = ref();
const parentAgentUserSelectRef = ref();
// 店铺选择组件引用
const agentShopSelectRef = ref();

// 表单数据
const formData = reactive({
	agentlevel: 0,
	agentUserId: null, // 使用null而不是空字符串，保持与Number类型一致
	agentShopIds: [],
	parentAgentId: 0
});

// 表单验证规则
const rules = {
	agentLevel: [{ required: true, message: '代理层级不能为空', trigger: 'change' }],
	agentUserId: [{ required: true, message: '请选择代理商', trigger: 'change' }],
	agentShopIds: [{ required: true, message: '请选择代理商商户', trigger: 'change' }]
};

// 监听visible变化，加载代理商详情
watch(
	() => props.visible,
	newVal => {
		console.log('Agent Edit View - visible changed:', props.agentObj);
		if (newVal) {
			// 清空选择表格数据
			if (agentUserSelectRef.value && agentUserSelectRef.value.clearTableData) {
				agentUserSelectRef.value.clearTableData();
			}
			if (parentAgentUserSelectRef.value && parentAgentUserSelectRef.value.clearTableData) {
				parentAgentUserSelectRef.value.clearTableData();
			}
			// 清空店铺选择表格数据
			if (agentShopSelectRef.value && agentShopSelectRef.value.clearTableData) {
				agentShopSelectRef.value.clearTableData();
			}

			// 设置代理层级为父组件传来的值
			formData.agentlevel = props.agentLevel;
			// 直接设置当前代理商ID，确保agent-user-select组件能够接收到正确的值
			formData.agentUserId = Number(props.agentUserId) || null; // 确保是数字类型
			// 设置父代理商ID
			if (props.parentId) {
				formData.parentAgentId = props.parentId;
			}
			// console.log('Agent Edit View - Form data initialized:', formData);
		}
	}
);

// 加载代理商详情
// const loadAgentDetail = async () => {
// 	try {
// 		const res = await service.agent.agent.getAgentDetail({ id: props.agentId });
// 		if (res) {
// 			// 填充表单数据
// 			formData.agentUserId = res.agentUserId;
// 			formData.agentShopIds = res.agentShopIds || '';
// 			formData.parentAgentId = res.parentAgentId || 0;
// 		}
// 	} catch (error) {
// 		ElMessage.error('加载代理商详情失败');
// 	}
// };

// 重置表单
const resetForm = () => {
	if (formRef.value) {
		formRef.value.resetFields();
	}

	// 清空表单数据，确保与merchant-select和agent-user-select组件绑定的值被重置
	formData.level = null;
	formData.agentUserId = null; // 使用null而不是空字符串，保持与Number类型一致
	formData.agentShopIds = '';
	formData.parentAgentId = 0;
};

// 关闭弹窗
const handleClose = () => {
	// 清空表单数据，确保agent-user-select组件的v-model被重置
	formData.agentUserId = null; // 使用null而不是空字符串
	formData.parentAgentId = 0;
	resetForm();
	emit('update:visible', false);
};

// 提交表单
const handleSubmit = async () => {
	try {
		// 表单验证
		await formRef.value.validate();
		if (formData.parentAgentId == null) {
			formData.parentAgentId = formData.parentAgentId;
		}
		// 构建提交数据
		const submitData = {
			...formData,
			parentId: props.parentId,
			id: props.agentId // 添加agentId用于更新
		};
		console.log(submitData);
		// 调用更新代理商API
		const res = await service.agent.agent.updateAgent(submitData);

		if (res) {
			// 更新成功，触发成功事件
			emit('success');
			resetForm();
			emit('update:visible', false);

			// 显示成功提示
			ElMessage.success('编辑代理商成功');
		} else {
			// 显示错误提示
			ElMessage.error(res.msg || '编辑代理商失败');
		}
	} catch (error) {
		// 验证失败不做处理
	}
};
</script>
